package com.jzcn.common.file;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;

public class StoreFileProcessRunnable implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(StoreFileProcessRunnable.class);

    protected String storeFileName;
    protected byte[] fileBytes;
    protected String fileSuffix;
    protected Date fileCreateDate;
    protected String fileStorePrefix;

    protected Integer id;

    public StoreFileProcessRunnable(byte[] fileBytes, String storeFileName,  String fileSuffix, Date fileCreateDate, Integer id, String fileStorePrefix) {
        super();
        this.fileBytes = fileBytes;
        this.storeFileName = storeFileName;
        this.fileSuffix = fileSuffix;
        this.fileCreateDate = fileCreateDate;
        this.id = id;
        this.fileStorePrefix = fileStorePrefix;
    }

    public StoreFileProcessRunnable() {

    }

    protected File storeFile(String storeRelativePath, String fileStorePrefix, byte[] fileBytes) throws IOException {
        //将图片复制加到线程中
        if (!StringUtils.isEmpty(storeRelativePath)) {
            File file = new File(fileStorePrefix + storeRelativePath);
            ByteArrayInputStream bais = new ByteArrayInputStream(fileBytes);
            FileUtils.copyInputStreamToFile(bais, file);
            return file;
        }
        return null;
    }

    public void run() {
        try {
            String relativePath = RelativePathGenerator.generate(storeFileName, fileSuffix, fileCreateDate);
            this.storeFile(relativePath, fileStorePrefix, fileBytes);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

}
